import React, {useMemo} from 'react'
import {HelpText} from './HelpText'

interface FormGroupLabelProps {
  label?: string
  feedback?: React.ReactElement | string
  id?: string
  className?: string
  isRequired?: boolean
  helpText?: React.ReactNode
  valid?: boolean
  invalid?: boolean
}

const FormGroupLabel: React.FC<FormGroupLabelProps> = ({
  className,
  id,
  helpText,
  isRequired,
  label,
  feedback,
  children,
  valid,
  invalid,
}): React.ReactElement => {
  const renderHelpText = useMemo(() => {
    return <HelpText>{helpText}</HelpText>
  }, [helpText])

  const renderFeedback = useMemo(() => {
    if (feedback) {
      return (
        <p className={'mb-0 feedback ' + (invalid ? 'invalid ' : '') + (valid ? 'valid ' : '')}>
          {feedback}
        </p>
      )
    } else {
      return null
    }
  }, [feedback, invalid, valid])

  return (
    <div className={'form-group ' + (className ? className : '')}>
      {label && (
        <label htmlFor={id} className={'label-size '}>
          {label + (isRequired ? '*' : '')}
        </label>
      )}
      {children}
      {renderFeedback}
      {renderHelpText}
    </div>
  )
}

export {FormGroupLabel}
